package com.hupu.jrs.ui.splash

import android.content.Context
import com.alibaba.fastjson.JSON
import com.hupu.jrs.Constants
import com.hupu.jrs.bean.UpdateInfo
import com.hupu.jrs.components.okhttp.OkHttpHelper
import com.hupu.jrs.injector.PerActivity
import com.hupu.jrs.util.ChannelUtil
import com.hupu.jrs.util.SettingPrefUtil
import com.umeng.analytics.MobclickAgent
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.concurrent.TimeUnit
import javax.inject.Inject

/**
 * Created by sll on 2016/5/31.
 */
@PerActivity
class SplashPresenter @Inject
constructor(private val mContext: Context, private val mOkHttpHelper: OkHttpHelper) : SplashContract.Presenter {

    private var mSplashView: SplashContract.View? = null
    private var mSubscription: Subscription? = null

    override fun initUmeng() {
        val config = MobclickAgent.UMAnalyticsConfig(mContext, "55f1993be0f55a0fd9004fbc",
                ChannelUtil.getChannel(mContext))
        MobclickAgent.startWithConfigure(config)
    }

    override fun initHuPuSign() {
        mSubscription = Observable.create<UpdateInfo> { subscriber ->
            try {
                val result = mOkHttpHelper.getStringFromServer(Constants.UPDATE_URL)
                subscriber.onNext(JSON.parseObject<UpdateInfo>(result, UpdateInfo::class.java))
            } catch (e: Exception) {
                subscriber.onError(e)
            }

            subscriber.onCompleted()
        }.timeout(5, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ updateInfo ->
                    if (updateInfo != null) {
                        if (updateInfo!!.extra != null) {
                            SettingPrefUtil.setNeedExam(mContext, updateInfo!!.extra!!.needExam === 1)
                        }
                        SettingPrefUtil.setHuPuSign(mContext, updateInfo!!.hupuSign!!)
                    }
                    mSplashView!!.showMainUi()
                }) { throwable ->
                    throwable.printStackTrace()
                    mSplashView!!.showMainUi()
                }
    }

    override fun attachView(view: SplashContract.View) {
        mSplashView = view
    }

    override fun detachView() {
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mSplashView = null
    }
}
